package com.example.tangyee.fragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.animation.FastOutLinearInInterpolator;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tangyee.R;
import com.example.tangyee.activity.KnowledgeDetailActicity;
import com.example.tangyee.activity.KnowledgeMenuActivity;
import com.example.tangyee.adapter.MyRecyclerViewAdapter;
import com.example.tangyee.bean.Article;
import com.example.tangyee.utils.GetArticles;
import com.example.tangyee.utils.GetKnowledgeMenuItems;
import com.example.tangyee.utils.GlideApp;
import com.example.tangyee.view.MyCenterPopup;
import com.lxj.xpopup.XPopup;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class KnowledgeFragment extends Fragment {

    public static KnowledgeFragment newInstance() {
        return new KnowledgeFragment();
    }

    private Unbinder mUnbinder;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.fab)
    FloatingActionButton fab;

    private boolean fabIsShow = true;

    private int page = 1;
    private List<Article> data = new ArrayList<>();
    private MyRecyclerViewAdapter<Article> mAdapter;
    private View footView;
    private LinearLayoutManager layoutManager;
    private GetArticles.OnPostExecute execute;

    // 防止总在加载
    private boolean isLoading = false;

    boolean isClear = false;

    private RefreshLayout refreshLayout;

    private GetArticles mGetArticles;
    private GetKnowledgeMenuItems mGetKnowledgeMenuItems;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content_knowledge, container, false);
        mUnbinder = ButterKnife.bind(this,view);

        /*
         * 下拉刷新
         * */
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new MaterialHeader(getActivity()));
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            if (mGetArticles != null) {
                mGetArticles.cancel(true);
            }
            ProgressBar progressBar = footView.findViewById(R.id.progressBar);
            progressBar.setVisibility(View.VISIBLE);
            TextView textView = footView.findViewById(R.id.loading);
            textView.setText("努力加载中···");
            page = 1;
            isClear = true;
            mGetArticles = new GetArticles(page, 30, execute);
            mGetArticles.execute();
        });

        // 初始化RecyclerView
        initRecyclerView();

        return view;
    }

    @OnClick(R.id.fab)
    public void showMenu() {
        showMenuDialog(0, "知识分类");
    }

    private int supId = 0;
    private void showMenuDialog(int parentId, String title) {
        XPopup.get(getActivity()).asLoading().show("loading");
        GetKnowledgeMenuItems.OnPostExecute executeForMenu = items -> {
            XPopup.get(getActivity()).dismiss("loading");
            if (items == null) {
                Toast.makeText(getActivity(), "请求超时", Toast.LENGTH_SHORT).show();
                return;
            }
            if (items.size() == 0) {
                Intent intent;
                if (supId == 0) {
                    intent = KnowledgeMenuActivity.getKnowledgeMenuActivityIntent(getActivity(), parentId, 0);
                } else {
                    intent = KnowledgeMenuActivity.getKnowledgeMenuActivityIntent(getActivity(), supId, parentId);
                }
                getActivity().startActivity(intent);
                return;
            }
            String[] titles = new String[items.size()];
            for (int i = 0; i < items.size(); i ++) {
                titles[i] = items.get(i).getCategory();
            }
            /*XPopup.get(getActivity()).dismiss();*/
            XPopup.get(getActivity()).asCustom(new MyCenterPopup(getActivity(), titles, new MyCenterPopup.PopupHelper(){
                @Override
                public String getTitle() {
                    return title;
                }

                @Override
                public void onSelect(View view, int position) {
                    supId = parentId;
                    showMenuDialog(items.get(position).getId(), ((TextView)view).getText().toString());
                }
            })).show();

        };
        mGetKnowledgeMenuItems = new GetKnowledgeMenuItems(parentId, executeForMenu);
        mGetKnowledgeMenuItems.execute();
    }

    /*初始化RecyclerView*/
    private void initRecyclerView() {
        mAdapter = new MyRecyclerViewAdapter<>(data, getActivity(), R.layout.article_item_list_layout);
        footView = LayoutInflater.from(getActivity()).inflate(R.layout.item_foot_layout,null);
        mAdapter.addFooterView(footView);
        mAdapter.setItemViewHelper(new MyRecyclerViewAdapter.ItemViewHelper<Article>() {

            @Override
            public void onClick(View view, Article article) {
                Intent intent = new Intent(getActivity(), KnowledgeDetailActicity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("knowID", article.getKnowID());
                bundle.putString("title", article.getTitle());
                intent.putExtras(bundle);
                getActivity().startActivity(intent);
            }

            @Override
            public void onBindViewHolder(MyRecyclerViewAdapter.MyHolder holder, int position, Article article) {
                TextView title = holder.itemView.findViewById(R.id.title);
                title.setText(article.getTitle());
                TextView releaseDate = holder.itemView.findViewById(R.id.release_date);
                releaseDate.setText( article.getAuthor() + "    " + article.getReleaseDate() + "    " + article.getCount() + "访问");
                TextView summary = holder.itemView.findViewById(R.id.summary);
                summary.setText(article.getSummary());

                ImageView image = holder.itemView.findViewById(R.id.image);
                GlideApp.with(getActivity())
                        .load(article.getImageUrl())
                        .placeholder(R.drawable.loading)
                        .error(R.drawable.error)
                        .fitCenter()
                        .into(image);
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        layoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(layoutManager);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    //调用方法
                    if (dy > 0 && fabIsShow) {
                        hide(fab);
                        fabIsShow = false;
                    } else if (dy < 0 && !fabIsShow) {
                        show(fab);
                        fabIsShow = true;
                    }
                }
            });
        }

        execute = articles -> {
            if (articles == null) {
                if (refreshLayout != null)
                    refreshLayout.finishRefresh(false);
                ProgressBar progressBar = footView.findViewById(R.id.progressBar);
                progressBar.setVisibility(View.GONE);
                TextView textView = footView.findViewById(R.id.loading);
                textView.setText("请求超时···");
            } else if (articles.size() == 0) {
                if (refreshLayout != null)
                    refreshLayout.finishRefresh(true);
                ProgressBar progressBar = footView.findViewById(R.id.progressBar);
                progressBar.setVisibility(View.GONE);
                TextView textView = footView.findViewById(R.id.loading);
                textView.setText("没有数据了···");
            } else {
                ++ page;
                if (refreshLayout != null)
                    refreshLayout.finishRefresh(true);
                int count = mAdapter.getItemCount();
                mAdapter.updateDate(articles, isClear);

                if (count <= 1 || isClear) {
                    isClear = false;
                    ScaleAnimation sa = new ScaleAnimation(1f, 1f, 1.1f, 1f,
                            Animation.RELATIVE_TO_SELF, 0f,
                            Animation.RELATIVE_TO_SELF, 0f);
                    sa.setDuration(1000);

                    AlphaAnimation aa = new AlphaAnimation(0, 1);
                    aa.setDuration(1000);

                    AnimationSet as = new AnimationSet(true);
                    as.setDuration(1000);
                    as.addAnimation(sa);
                    as.addAnimation(aa);

                    mRecyclerView.startAnimation(as);
                }
            }
            isLoading = false;
        };
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == mAdapter.getItemCount() && !isLoading) { // footItem 可见时，说明该加载更多了。
                    Log.d("test", "loading executed");
                    isLoading = true;
                    mGetArticles = new GetArticles( page, 30, execute);
                    mGetArticles.execute();
                }
            }

            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                /*glide优化，提升性能?*/
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    GlideApp.with(getActivity()).resumeRequests();
                }else {
                    GlideApp.with(getActivity()).pauseRequests();
                }
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mGetKnowledgeMenuItems != null) {
            mGetKnowledgeMenuItems.cancel(true);
        }
        if (mGetArticles != null) {
            mGetArticles.cancel(true);
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }


    /**
     * 显示的动画
     */
    private void show(final View view) {
        view.animate().cancel();

        view.setAlpha(0f);
        view.setScaleY(0f);
        view.setScaleX(0f);

        view.animate()
                .scaleX(1f)
                .scaleY(1f)
                .alpha(1f)
                .setDuration(200)
                .setInterpolator(new LinearOutSlowInInterpolator())
                .setListener(new AnimatorListenerAdapter() {

                    @Override
                    public void onAnimationStart(Animator animation) {
                        view.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {

                    }
                });
    }

    /**
     * 隐藏的动画
     */
    private void hide(final View view) {
        view.animate().cancel();
        view.animate()
                .scaleX(0f)
                .scaleY(0f)
                .alpha(0f)
                .setDuration(200)
                .setInterpolator(new FastOutLinearInInterpolator())
                .setListener(new AnimatorListenerAdapter() {
                    private boolean mCancelled;

                    @Override
                    public void onAnimationStart(Animator animation) {
                        view.setVisibility(View.VISIBLE);
                        mCancelled = false;
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                        mCancelled = true;
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        if (!mCancelled) {
                            view.setVisibility(View.INVISIBLE);
                        }
                    }
                });
    }
}
